package com.jd.jstable.strategy.jim;

import com.alibaba.fastjson.JSON;
import com.jd.jim.cli.Cluster;
import com.jd.jstable.config.KeyMaker;
import com.jd.jstable.config.KeyMode;
import com.jd.jstable.strategy.ExpireTimeStrategy;
import com.jd.jstable.strategy.ResetableStrategy;
import com.jd.jstable.strategy.StrategyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenyipu on 2018/6/1.
 */
@Service("MD5_138cc4666fbd6262a0a57cab833c5dbc_jim")
public class JimRedisStrategy extends ExpireTimeStrategy  implements ResetableStrategy, KeyMaker {

    public final String prefix = "JSTABLE";
    @Autowired
    @Qualifier("jstable_______JimClient")
    Cluster jimClient;

    @Override
    public Object solve(Object invoker, Method method, Object[] args, String param, KeyMode keyMode) {
        String key = generate(invoker, method, args, keyMode);
        String resultLast = jimClient.get(key);
        if (null == resultLast) {
            return null;
        }
        return JSON.parseObject(resultLast, method.getReturnType());
    }

    @Override
    public void expire(Object invoker, Method method, Object[] args, Object result, Long time, TimeUnit timeUnit, KeyMode keyMode) {
        String key = generate(invoker, method, args, keyMode);
        jimClient.set(key, JSON.toJSONString(result));
        if(timeUnit==null){
            return;
        }
        jimClient.expire(key, time, timeUnit);
    }

    @Override
    public String generate(Object invoker, Method method, Object[] args, KeyMode keyMode) {
        return String.format("%s_%s_%s", prefix, keyMode.getPrefix(), StrategyUtil.makeResourceKey(invoker.getClass(), method.getName(), args, keyMode));
    }

    @Override
    public void reset(Object invoker, Method method, Object[] args, String param, KeyMode keyMode) {
        String key = generate(invoker, method, args, keyMode);
        jimClient.del(key);
    }
}
